package com.madixin.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.madixin.chat.exception.ChatBaseException;
import com.madixin.chat.exception.ErrorCode;
import com.madixin.chat.mapper.ChatMessageMapper;
import com.madixin.chat.model.ChatMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class ChatMessageService extends ServiceImpl<ChatMessageMapper, ChatMessage> {
    private static final Logger LOGGER = LoggerFactory.getLogger(ChatMessageService.class);
    
    public List<ChatMessage> getConversationMessage(String sessionId, int page, int size) throws ChatBaseException {
        try {
            // 确保页码和每页大小有效
            if (page < 1) {
                page = 1;
            }
            if (size < 1) {
                size = 10;
            }

            // 创建查询条件，按会话ID过滤
            LambdaQueryWrapper<ChatMessage> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ChatMessage::getSessionId, sessionId);
            
            // 按创建时间降序排序，最新的消息排在前面
            queryWrapper.orderByAsc(ChatMessage::getCreateTime);
            
            // 使用Page对象进行分页查询
            Page<ChatMessage> pageParam = new Page<>(page, size);
            Page<ChatMessage> resultPage = this.page(pageParam, queryWrapper);
            
            LOGGER.info("分页查询结果：总记录数={}，总页数={}，当前页记录数={}", 
                    resultPage.getTotal(), resultPage.getPages(), resultPage.getRecords().size());
            
            // 返回查询结果列表
            return resultPage.getRecords();
        } catch (Exception e) {
            LOGGER.error("Fail to get messages for conversation，sessionId = " + sessionId, e);
            throw new ChatBaseException(ErrorCode.FAIL_GET_SESSION_MESSAGE);
        }
    }

    public void insertMessage(String sessionId, ChatMessage message)throws ChatBaseException  {
        try {
            // 设置会话ID
            message.setSessionId(sessionId);
            // 如果创建时间为空，设置当前时间
            if (message.getCreateTime() == null) {
                message.setCreateTime(new Date());
            }
            // 使用MyBatis-Plus的save方法保存消息
            boolean success = this.save(message);
        }catch (Exception e) {
            LOGGER.error("Fail to insert messages for conversation，sessionId = " + sessionId, e);
            throw new ChatBaseException(ErrorCode.FAIL_INSERT_SESSION_MESSAGE);
        }
    }
}
